<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="文章属性" prop="flag">
        <el-input
          v-model="queryParams.flag"
          placeholder="请输入'文章类型属性：0新闻类，1其他类',"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['content:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['content:type:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['content:type:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['content:type:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" :index="createIndex" />
       <el-table-column label="一级分类" align="center" prop="name" />
       <el-table-column label="归属类型" align="center" prop="flag">
      <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_article_type" :value="scope.row.flag"/>
        </template>
      </el-table-column>
      <el-table-column label="二级分类" align="center" prop="secondTypes">
       <template slot-scope="scope">
        <el-row v-if="scope.row.secondTypes!=0">
        <el-row v-for=" (itme,index) in getArray(scope.row.secondTypes)"  :key="index">
          <el-tag 
          :tab-position="tabPosition"
         
          type="warning"
          closable
          @close="handleClose(itme)" >{{itme.name}}
           </el-tag>
        </el-row>
          </el-row>
          <el-row>
            <el-button size="mini" icon="el-icon-plus" circle type="danger" @click="addSecoad(scope.row)"></el-button>
          </el-row>
       </template>
      </el-table-column>
      <el-table-column label="图标" align="center" prop="iconUrl" >
         <!-- 图片的显示 -->
                 <template   slot-scope="scope">            
                    <img :src="scope.row.iconUrl"  min-width="70px" height="70px" 
                           @click="previewPic(scope.row.iconUrl)" />
                 </template>     
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="linkUrl" />
      <el-table-column label="排序" align="center" prop="serial" />
      <el-table-column label="状态" align="center" prop="status">
      <template slot-scope="scope">
          <el-switch  v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['content:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['content:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

<!-- 图片预览   放在表格外面，这是个弹出框-->
      <el-dialog :visible.sync="dialogVisible" :modal="false" title="图片预览" width="50%">
        <img :src="previewpic" alt=""  width="100%" />
        <span slot="footer" class="dialog-footer">
          </span>
       </el-dialog>
  <!-- 图片预览 -->

 <el-dialog :title="title" :visible.sync="secodOpen" width="30%" append-to-body>
 <el-form ref="secodForm" :model="secodForm" :rules="rules" label-width="100px">
   <el-form-item label="二级分类名称" prop="serial">
        <el-input v-model="secodForm.name" placeholder="请输入二级分类名称" />
        </el-form-item>
        <el-form-item label="二级分类排序" prop="serial">
        <el-input v-model="secodForm.serial" placeholder="请输入二级分类排序" />
        </el-form-item>
 </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSecodForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
 </el-dialog>
    <!-- 添加或修改所属类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文章类型" prop="flag">
          <el-select v-model="form.flag" placeholder="请选择">
          <el-option
            v-for="dict in dict.type.sys_article_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="一级分类" prop="name">
          <el-input v-model="form.name" placeholder="请输入一级分类" />
        </el-form-item>
            <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" type="text" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="排序" prop="serial">
          <el-input v-model="form.serial" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="图片地址" prop="iconUrl">
           <el-upload
          class="avatar-uploader"
          ref="upload"
          :action="upload.url"
          :headers="upload.headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <span>注意：像素为120x120</span>
        </el-form-item>
        <el-form-item label="角色权限">
        <el-form :model="roleQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="roleQueryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter.native="handleRoleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleRoleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
        </el-form-item>
      </el-form>
       <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="添加时间" align="center" prop="createTime" />
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="roleQueryParams.pageNum"
      :limit.sync="roleQueryParams.pageSize"
      @pagination="getRoleList"
    />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType,changeNoticeStatus,addSecondType,delSecondType } from "@/api/content/type";
import { listRole } from "@/api/allocation/role";
import { getToken } from "@/utils/auth";
export default {
  name: "Type",
   dicts: ['sys_article_type'],
  data() {
    return {
      
       dialogVisible: false,
        previewpic: "",
      // 遮罩层
      loading: true,
    tabPosition: 'left',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 所属类型表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示二级分类弹出层
      secodOpen:false,
      upload:{
         // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/content/type/importData"
    },
    //角色表格数据
    roleList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        asId: null,
        flag: null,
        name: null,
        iconUrl: null,
        linkUrl: null,
        serial: null,
        status: '0'
      },
      //角色查询参数
      roleQueryParams:{
        pageNum:1,
        pageSize:10,
        roleName:null,
      },
      //图片地址
      imageUrl:'',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //二级分类表单数据
      secodForm:{
        parentId:"",
        name:'',
        serial:''
      }
    };
  },
  created() {
    this.getList();
    this.getRoleList();
  },
  methods: {
    createIndex(index){
        return (this.queryParams.pageNum - 1)* this.queryParams.pageSize + index +1;
    },
    //查询角色数据
    getRoleList(){
      listRole(this.roleQueryParams).then(res=>{
        console.info(res);
        this.roleList=res.rows;
        this.total=res.total;
      })
    },
//将二级分类的数据进行遍历，加入数组中
    getArray(data){
      let array=[]
      if(data&&data.length!==0){
        data.forEach(item => {
          array.push(item)
        });
        return array;
      }
    },
    //删除二级分类数据
    handleClose(tag) {
       console.info(tag.id);
       const id = tag.id;
      this.$modal.confirm('是否确认删除所属类型编号为"' + id + '"的数据项？').then(function() {
        return delSecondType(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      },
    /** 查询所属类型列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(res => {
        console.info(res);
        this.typeList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
     // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.id + '"分类吗？').then(function() {
        return changeNoticeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
      //图片放大
      previewPic(url) {
           this.previewpic = url;
           this.dialogVisible = true;
        },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        asId: null,
        flag: null,
        name: null,
        iconUrl: null,
        linkUrl: null,
        serial: null,
        createTime: null,
        updateTime: null,
        status: 0,
        roleId:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //查询角色数据
    handleRoleQuery(){
      this.roleQueryParams.pageNum=1;
      this.getRoleList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加所属类型";
    },
//新增二级分类
    addSecoad(row) {
      console.info(row.id);
      this.secodForm.parentId=row.id;
      this.secodOpen = true;
      this.title = "添加二级分类";
    },
    //保存二级分类数据
    submitSecodForm(){
      this.$refs["secodForm"].validate(valid => {
        if (valid) {
            addSecondType(this.secodForm).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.secodOpen = false;
              this.getList();
            });
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getType(id).then(response => {
        this.form = response.data;
        this.imageUrl =response.data.iconUrl;
        
        this.open = true;
        this.title = "修改所属类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.roleId=this.ids;
          if (this.form.id != null) {
            updateType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //上传图片操作
     handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res.code==200){
          console.res.data;
          this.form.iconUrl=res.data;
        }else{
          console.error(res.msg)
        }
      },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所属类型编号为"' + ids + '"的数据项？').then(function() {
        return delType(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('content/type/export', {
        ...this.queryParams
      }, `type_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
